/*
 * JTalkerClientFront.java
 *
 * Created on 27. Oktober 2003, 11:11
 */

package com.jtalker.client;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;

import com.jtalker.client.JTalkerClient.MemberData;

/**
 * 
 * @author ChrM
 */
public class JTalkerClientFront extends JFrame implements ActionListener, JTalkerClientCommandInterface {

	private static final long serialVersionUID = 1L;

	/** Creates new form JTalkerClientFront */
	public JTalkerClientFront(JTalkerClient clent) {
		// Init GUI
		this.initComponents();
		this.setIconImage(new ImageIcon(cl.getResource("com/jtalker/rs/icons/jtalker.png")).getImage());

		// Init client
		if (clent == null) {
			this.theClient = new JTalkerClient();
		} else {
			this.theClient = clent;
		}
		this.jLabelVersion.setText(JTalkerClient.RELEASE); // Footer version info

		// Add List model
		this.jListMembers.setCellRenderer(new MyCellRenderer(this));
		this.jListMembers.setModel(this.theClient.memberList);

		MouseListener mouseListener = new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					// int index = list.locationToIndex(e.getPoint());
					writeMessageActionPerformed(null);
				}
			}

			public void mousePressed(MouseEvent e) {
				maybeShowPopup(e);
			}

			public void mouseReleased(MouseEvent e) {
				maybeShowPopup(e);
			}
		};

		this.jListMembers.addMouseListener(mouseListener);

		// Init Timer for updating the User List
		UpdateTimer ut = new UpdateTimer(this);
		ut.start();

		// Ok, client is ready, lets try to load plugins!
		if (this.loadAllPlugins()) {
			this.updatePluginShortcuts();
		}
		this.theClient.setFrontend(this);
		this.theClient.registerForCommandResponse(this);
	}

	/** Gets the PluginLoader */
	public JTalkerClientPluginLoader getPluginLoader() {
		return this.myPluginLoader;
	}

	/** Loads all Plugins and generates some extra menus */
	public boolean loadAllPlugins() {
		try {
			// First remove all Submenus
			this.jMenuPlugins.removeAll();

			if (this.myPluginLoader == null) {
				System.out.println("[PLUGIN]: Loader not exists now - create object");
				this.myPluginLoader = new JTalkerClientPluginLoader(this);
			} else {
				// Clear list

			}

			System.out.println("[PLUGIN]: Reload all plugins");
			if (!this.myPluginLoader.initPlugins(this.theClient.pluginDir)) {
				return false;
			}

			// Create menus for loaded plugins
			String[] allPlugins = this.myPluginLoader.getPluginClassNames();

			if (allPlugins != null) {
				for (int i = 0; i < allPlugins.length; i++) {
					this.createPluginMenuFor(allPlugins[i]);
				}
			}

			// Ok, all Plugins added, create Overview MenuItem
			this.jMenuPlugins.addSeparator();
			PlugInMenuItem tmpSettings = new PlugInMenuItem("Overview", 2);
			tmpSettings.setText("Plugin Overview...");
			tmpSettings.addActionListener(this);
			this.jMenuPlugins.add(tmpSettings);

		} catch (Exception e) {
			System.err.println("*** Can't load plugins: " + e.toString());
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/** Creates a menu structure for a plugin */
	private boolean createPluginMenuFor(String className) {
		// Create top menu
		JMenu tmpMenu = new JMenu();
		tmpMenu.setText(this.myPluginLoader.getPluginByClassName(className).getName());

		// Create Items
		PlugInMenuItem tmpMainGUI = new PlugInMenuItem(className, 0);
		tmpMainGUI.setText("Open Dialog...");
		tmpMainGUI.addActionListener(this);
		tmpMenu.add(tmpMainGUI);

		PlugInMenuItem tmpSettings = new PlugInMenuItem(className, 1);
		tmpSettings.setText("Plugin Settings...");
		tmpSettings.addActionListener(this);
		tmpMenu.add(tmpSettings);

		this.jMenuPlugins.add(tmpMenu);

		return true;
	}

	/** ActionListener Interface implementaion */
	public void actionPerformed(ActionEvent e) {
		PlugInMenuItem tmpItem = (PlugInMenuItem) e.getSource();

		if (tmpItem.type == 0) {
			this.openPluginMainGUIFor(tmpItem.pluginClass);
		} else if (tmpItem.type == 1) {
			this.openPluginSettingsGUIFor(tmpItem.pluginClass);
		} else if (tmpItem.type == 2) {
			if (this.myPluginsInfoDialog == null) {
				this.myPluginsInfoDialog = new JTalkerClientPluginsInfo(this);
			}
			if (this.myPluginsInfoDialog.updatePluginList(null)) {
				this.myPluginsInfoDialog.setVisible(true);
			}
		}
	}

	/** Opens Plugins Main GUI */
	private void openPluginMainGUIFor(String pluginClassName) {
		System.out.println("Main: " + pluginClassName);
		this.myPluginLoader.showPluginsGUI(pluginClassName, 0);
	}

	/** Opens Plugins Settings GUI */
	private void openPluginSettingsGUIFor(String pluginClassName) {
		System.out.println("Settings: " + pluginClassName);
		this.myPluginLoader.showPluginsSettings(pluginClassName, 0);
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
	 * content of this method is always regenerated by the Form Editor.
	 */
	private void initComponents() {// GEN-BEGIN:initComponents
		jPanelStatus = new JPanel();
		jLabelVersion = new JLabel();
		jLabelStatusConnect = new JLabel();
		jPanelToolsT = new JPanel();
		jToolBar1 = new JToolBar();
		jButtonConnect = new JButton();
		jToggleButtonStatus = new JToggleButton();
		// jComboBoxRefresh = new JComboBox();
		jButton1 = new JButton();
		jButtonConfig = new JButton();
		jPanelToolsR = new JPanel();
		jToolBar2 = new JToolBar();
		jButtonOpen = new JButton();
		jButtonMail = new JButton();
		jButtonReload = new JButton();
		jPanelMamberList = new JPanel();
		jScrollPaneMembers = new JScrollPane();
		jListMembers = new JList();
		jMenuBarMain = new JMenuBar();
		jMenuFile = new JMenu();
		jMenuItemClose = new JMenuItem();
		jMenuItemSettings = new JMenuItem();
		jMenuServer = new JMenu();
		jMenuItemAccount = new JMenuItem();
		jMenuItemConnect = new JMenuItem();
		jMenuItemCommand = new JMenuItem();
		jMenuItemChatroom = new JMenuItem();
		jMenuItemAbout = new JMenuItem();
		jMenuStatus = new JMenu();
		jMenuPlugins = new JMenu();
		jMenuAbout = new JMenu();
		jCheckBoxMenuItemBusy = new JCheckBoxMenuItem();
		jCheckBoxMenuItemBusy.setSelected(false);
		cl = ResourceAnchor.class.getClassLoader();
		connectEncrypted = new ImageIcon(cl.getResource("com/jtalker/rs/icons/encrypted.png"));
		connectPlainText = new ImageIcon(cl.getResource("com/jtalker/rs/icons/decrypted.png"));
		jPanelPlugIns = new JPanel();

		this.setTitle("JTalker");
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent evt) {
				exitForm(evt);
			}
		});

		/** -------------------------设置底部状态栏----------------------------- */
		jPanelStatus.setLayout(new BorderLayout());

		jLabelVersion.setBorder(new BevelBorder(BevelBorder.LOWERED));
		jPanelStatus.add(jLabelVersion, BorderLayout.CENTER);

		jLabelStatusConnect.setText("Ready");
		jLabelStatusConnect.setBorder(new BevelBorder(BevelBorder.LOWERED));
		jPanelStatus.add(jLabelStatusConnect, BorderLayout.EAST);

		this.getContentPane().add(jPanelStatus, BorderLayout.SOUTH);

		/** -------------------------设置工具栏----------------------------- */
		jPanelToolsT.setLayout(new BorderLayout());

		jToolBar1.setRollover(true);
		// jButtonConnect.setText("Connect");
		jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/connected.png")));
		jButtonConnect.setToolTipText("Connect/Disconnect");
		jButtonConnect.setMargin(new Insets(1, 2, 1, 2));
		jButtonConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				connectActionPerformed(evt);
			}
		});
		jToolBar1.add(jButtonConnect);

		// jToggleButtonStatus.setText("Busy");
		jToggleButtonStatus.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/go_busy.png")));
		jToggleButtonStatus.setToolTipText("Set status to busy");
		jToggleButtonStatus.setMargin(new Insets(1, 2, 1, 2));
		jToggleButtonStatus.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				if (jCheckBoxMenuItemBusy.isSelected()) {
					jCheckBoxMenuItemBusy.setSelected(false);
				} else {
					jCheckBoxMenuItemBusy.setSelected(true);
				}
				statusActionPerformed(evt);
			}
		});
		jToolBar1.add(jToggleButtonStatus);

		// jButton1.setText("Refresh");
		/*
		 * jButton1.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/reload.png")));
		 * jButton1.setToolTipText("Refresh now"); jButton1.setMargin(new Insets(1, 2, 1, 2));
		 * jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) {
		 * refreshActionPerformed(); } }); jToolBar1.add(jButton1);
		 */

		// jButtonConfig.setText("Config");
		jButtonConfig.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/configure.png")));
		jButtonConfig.setToolTipText("Configure JTalker");
		jButtonConfig.setMargin(new Insets(1, 2, 1, 2));
		jButtonConfig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				showSettings();
			}
		});
		jToolBar1.add(jButtonConfig);
		jToolBar1.addSeparator();

		this.jPanelPlugIns.setLayout(new GridLayout());
		jToolBar1.add(this.jPanelPlugIns);

		// jComboBoxRefresh.setModel(new DefaultComboBoxModel(new
		// String[] { "5 sec", "15 sec", "30 sec" }));
		// jComboBoxRefresh.setToolTipText("Refresh intervall");
		// jComboBoxRefresh.setMaximumSize(new Dimension(100, 32767));
		// jToolBar1.add(jComboBoxRefresh);

		jPanelToolsT.add(jToolBar1, BorderLayout.CENTER);

		this.getContentPane().add(jPanelToolsT, BorderLayout.NORTH);
		/** -------------------------设置右边工具栏----------------------------- */
		jPanelToolsR.setLayout(new BorderLayout());

		jToolBar2.setOrientation(SwingConstants.VERTICAL);
		jToolBar2.setRollover(true);
		// jButtonOpen.setText("Open");
		jButtonOpen.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/message_window.png")));
		jButtonOpen.setToolTipText("Open a chat window");
		jButtonOpen.setMargin(new Insets(1, 2, 1, 2));
		jButtonOpen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				writeMessageActionPerformed(evt);
			}
		});
		jToolBar2.add(jButtonOpen);

		jButtonMail.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/send_mail.png")));
		jButtonMail.setToolTipText("Send a mail to selected users");
		jButtonMail.setMargin(new Insets(1, 2, 1, 2));
		jButtonMail.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				writeMailActionPerformed(evt);
			}
		});
		jToolBar2.add(jButtonMail);

		// jButtonReload.setText("Reload");
		// jToolBar2.add(jButtonReload);
		jPanelToolsR.add(jToolBar2, BorderLayout.CENTER);
		this.getContentPane().add(jPanelToolsR, BorderLayout.EAST);
		/** -------------------------设置中部人员登录列表----------------------------- */
		jPanelMamberList.setLayout(new GridLayout());
		jScrollPaneMembers.setViewportView(jListMembers);
		jPanelMamberList.add(jScrollPaneMembers);
		this.getContentPane().add(jPanelMamberList, BorderLayout.CENTER);
		/** -------------------------设置顶部菜单----------------------------- */
		jMenuFile.setText("Client");
		jMenuItemClose.setText("Exit");
		jMenuItemClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				exitForm(null);
			}
		});

		jMenuItemSettings.setText("Settings...");
		jMenuItemSettings.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				showSettings();
			}
		});

		jMenuFile.add(jMenuItemSettings);
		jMenuFile.addSeparator();
		jMenuFile.add(jMenuItemClose);

		jMenuBarMain.add(jMenuFile);

		jMenuServer.setText("Server");
		jMenuItemAccount.setText("Create Account...");
		jMenuItemAccount.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				accountActionPerformed(null);
			}
		});
		jMenuServer.add(jMenuItemAccount);

		jMenuItemCommand.setText("Send Command...");
		jMenuItemCommand.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				commandActionPerformed(evt);
			}
		});
		jMenuServer.add(jMenuItemCommand);

		jMenuItemChatroom.setText("Create Chatroom...");
		jMenuItemChatroom.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				chatroomActionPerformed(evt);
			}
		});
		jMenuServer.add(jMenuItemChatroom);

		jMenuServer.addSeparator();

		jMenuItemConnect.setText("Connect/Disconnect");
		jMenuItemConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				connectActionPerformed(null);
			}
		});
		jMenuServer.add(jMenuItemConnect);

		jMenuBarMain.add(jMenuServer);

		jMenuStatus.setText("Status");
		jCheckBoxMenuItemBusy.setText("Busy");
		jCheckBoxMenuItemBusy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				if (jToggleButtonStatus.isSelected()) {
					jToggleButtonStatus.setSelected(false);
				} else {
					jToggleButtonStatus.setSelected(true);
				}
				statusActionPerformed(null);
			}
		});
		jMenuStatus.add(jCheckBoxMenuItemBusy);

		jMenuBarMain.add(jMenuStatus);

		// TODO: Plugins
		jMenuPlugins.setText("Plugins");
		jMenuBarMain.add(jMenuPlugins);

		jMenuAbout.setText("?");
		jMenuItemAbout.setText("About...");
		jMenuItemAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				JOptionPane
						.showMessageDialog(
								null,
								"JTalker "
										+ JTalkerClient.RELEASE
										+ "\nCopyright (C) 2009 by ChrM (http://www.chrm.info)\n\nThis program is free software; "
										+ "you can redistribute it and/or\nmodify it under the terms of the GNU General Public License "
										+ "as\npublished by the Free Software Foundation; either version 2 of\nthe License, or (at your "
										+ "option) any later version.\nThis program is distributed in the hope that it will be useful,"
										+ "\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS "
										+ "FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.",
								"About JTalker", JOptionPane.INFORMATION_MESSAGE);
			}
		});
		jMenuAbout.add(jMenuItemAbout);
		jMenuBarMain.add(jMenuAbout);
		setJMenuBar(jMenuBarMain);

		pack();
	}// GEN-END:initComponents

	/** Shows the setting dialog */
	private void showSettings() {
		if (this.mySettings == null) {
			this.mySettings = new JTalkerFrontSettings(this);
		}
		this.mySettings.setVisible(true);
	}

	/** Starts a browser with an URL */
	public boolean openBrowser(String _url) {
		String application;

		if (_url.startsWith("mailto:"))
			application = this.theClient.defaultMailer;
		else
			application = this.theClient.defaultBrowser;

		/*
		 * try { java.lang.Runtime.getRuntime().exec(application + " " + _url); } catch (Exception _e) {
		 * System.err.println("*** Can't execute process: " + _e.toString()); return false; }
		 */

		return ProcessExecuter.execute(application, _url, true);
	}

	/** Create a command send dialog */
	public void commandActionPerformed(ActionEvent evt) {
		if (this.myCommandDialog == null) {
			this.myCommandDialog = new JTalkerFrontCommand(this);
		}
		// this.myCommandDialog.show();
		this.myCommandDialog.setVisible(true);
	}

	/** Connection to server */
	public void connectActionPerformed(ActionEvent evt) {
		// Connect or disconnect to server
		// System.out.println("-------connectActionPerformed1-------" + this.isConnected);
		if (!this.isConnected) {
			if (this.theClient.connect()) {
				if (!this.theClient.savePassword) {
					// Password not saved - get it
					String retVal = JOptionPane.showInputDialog("Input password for \"" + this.theClient.userName
							+ "\"");
					if (retVal != null) {
						this.theClient.userPasswd = retVal;
					} else {
						this.theClient.closeConnection();
						return;
					}
				}
				// System.out.println("-------connectActionPerformed1-------" + this.isConnected);
				this.theClient.loginOnServer();
				// if(this.theClient.loginOnServer()) {
				/*
				 * this.isConnected = true; this.jLabel2.setText("Connected to " + this.theClient.getServerInfo());
				 * 
				 * if(this.theClient.useSSL) { this.jLabel2.setIcon(this.connectEncrypted); } else {
				 * this.jLabel2.setIcon(this.connectPlainText); }
				 * 
				 * this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/disconnected.png" )));
				 * this.theClient.memberList.propertyChanged(); } else {
				 * this.jLabel2.setText("Can't log in on server!"); }
				 */
				// System.out.println("-------connectActionPerformed1-------" + this.isConnected);
			} else {
				this.isConnected = false;
				this.jLabelStatusConnect.setText("Can't connect to " + this.theClient.getServerInfo());
				this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/connected.png")));
			}
		} else {
			this.theClient.closeConnection();
			this.jLabelStatusConnect.setText("You are disconnected now.");
			this.jLabelStatusConnect.setIcon(null);
			this.isConnected = false;
			this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/connected.png")));
		}
	}

	/** Sets needed values on connect/disconnect */
	private void connectionEstablished(boolean yes) {
		if (yes) {
			this.isConnected = true;
			this.jLabelStatusConnect.setText("Connected to " + this.theClient.getServerInfo());

			if (this.theClient.useSSL) {
				this.jLabelStatusConnect.setIcon(this.connectEncrypted);
			} else {
				this.jLabelStatusConnect.setIcon(this.connectPlainText);
			}

			this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/disconnected.png")));
			this.theClient.memberList.propertyChanged();
		} else {
			this.isConnected = false;
			this.jLabelStatusConnect.setText("Can't log in on server!");
		}
	}

	/** Creates a new Account on the server */
	private void accountActionPerformed(ActionEvent evt) {
		new CreateAccountWindow(this, true).setVisible(true);
	}

	/** Creates a new chatroom */
	private void chatroomActionPerformed(ActionEvent evt) {
		new CreateChatroomWindow(this, true).setVisible(true);
	}

	/** Opens the Chat Window */
	private void writeMessageActionPerformed(ActionEvent evt) {
		try {
			MemberData member = this.getSelectedUser();
			member.showChatWindow(this);
		} catch (Exception e) {
			return;
		}

		// JTalkerFrontChat chatWin = new JTalkerFrontChat(this, member);
		// chatWin.show();
	}

	/**
	 * A command answer will be send to us from the server using this method
	 * 
	 * @return true, if the _id belongs to our command
	 */
	public boolean setCommandAnswer(String _id, String _from, String _content) {
		// TODO: actions for all answers
		if (_id.equals("rmchat01")) {
			// Answer for remove chatroom!
		} else if (_id.equals("disconnect01")) {
			this.jLabelStatusConnect.setText("You are disconnected now.");
			this.jLabelStatusConnect.setIcon(null);
			this.isConnected = false;
			this.jButtonConnect.setIcon(new ImageIcon(cl.getResource("com/jtalker/rs/icons/connected.png")));
		}

		return false;
	}

	/** Tries to remove a chatroom */
	public void removeChatroom(String roomname) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::removeChatRoom(\"" + roomname + "\")", null, "command", null, "rmchat01");
	}

	/** Tries to add a user to a chatroom */
	public void addChatroomUser(String roomName, String userName) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::addChatRoomUser(\"" + roomName + "\", \"" + userName + ")", null, "command",
				null, "addchatuser01");
	}

	/** Tries to remove a user from a chat-room */
	public void removeChatroomUser(String roomName, String userName) {
		if (!this.theClient.isConnected) {
			return;
		}
		this.theClient.sendMessage("std::removeChatRoomUser(\"" + roomName + "\", \"" + userName + ")", null,
				"command", null, "rmchatuser01");
	}

	/** Opens a chat-window for the _first_ selected user */
	public void openChatWindow() {
		this.writeMessageActionPerformed(null);
	}

	/** Opens the Mail Window */
	private void writeMailActionPerformed(ActionEvent evt) {
		int ind[] = this.jListMembers.getSelectedIndices();
		if (ind.length <= 0) {
			return;
		}
		// Create "to:" String
		String msgSended = "";
		String receivers = "";
		for (int i = 0; i < ind.length; i++) {
			msgSended += ("- " + this.theClient.allMembers.get(ind[i]).short_name + "\n");
			receivers += this.theClient.allMembers.get(ind[i]).short_name + ";;";
		}

		String retVal = JOptionPane.showInputDialog("Message to: \n" + msgSended);
		if (retVal == null) {
			return;
		}
		retVal = "<i>[To: " + receivers.replaceAll(";;", ", ") + "]</i><br>" + retVal;

		// make HTML-compatible
		/*
		 * retVal = JTalkerClientProtocol.toHTMLString(retVal); retVal = retVal.replaceAll("&","&amp;"); retVal =
		 * retVal.replaceAll("<","&lt;"); retVal = retVal.replaceAll(">","&gt;");
		 */

		this.theClient.sendMessage(retVal, receivers);
		return;
	}

	/** Gets selected User */
	public MemberData getSelectedUser() {
		int index = this.jListMembers.getSelectedIndex();
		if (index == -1) {
			return null;
		}
		try {
			return this.theClient.allMembers.get(index);
		} catch (Exception e) {
			return null;
		}
	}

	/** Refresh List */
	public void refreshActionPerformed() {
		// Refreshes the list

		if (this.theClient.STATE == JTalkerClient.STATE_OFFLINE) {
			this.connectionEstablished(false);
		} else if (this.theClient.STATE == JTalkerClient.STATE_CONNECTED) {
			this.connectionEstablished(true);
		}
		if (this.isConnected) {
			/*
			 * if(!this.theClient.lookUp()) { System.out.println("*** Server doesn't response!");
			 * JOptionPane.showMessageDialog(null, "Server doesn't response! Check connection!",
			 * "Server doesn't response", JOptionPane.ERROR_MESSAGE); if(this.isConnected)
			 * this.connectActionPerformed(null); return; }
			 */

			// this.jListMembers.updateUI();
			this.theClient.memberList.propertyChanged();
		} else {
			this.jLabelStatusConnect.setText("You are not connected! Connect first.");
		}
	}

	/** Toggle users status */
	private void statusActionPerformed(ActionEvent evt) {
		if (this.jToggleButtonStatus.isSelected()) {
			this.theClient.userStatus = "busy";
		} else {
			this.theClient.userStatus = "normal";
		}

		if (this.isConnected) {
			this.theClient.lookUp();
			this.theClient.memberList.propertyChanged();
		}
	}

	/** Shows PopUp for a user */
	private void maybeShowPopup(MouseEvent e) {
		if (this.userPopup == null) {
			// Create PopUp
			this.userPopup = new JTalkerClientFrontPopUp(this);
		}

		if (e.isPopupTrigger()) {
			if (this.jListMembers.getFirstVisibleIndex() == -1) {
				return;
			}
			this.jListMembers.setSelectedIndex(this.jListMembers.locationToIndex(e.getPoint()));
			this.userPopup.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	/** Notify by incomming of new messages */
	private void notifyOnNewMessage(boolean enable, String text) {
		if (enable) {
			// Enable choosen notificator
			switch (this.theClient.newMailNotificationType) {
			case 0:
				break;
			case 1:
				this.toFront();
				break;
			case 2:
				if (this.newMessageNotificator == null) {
					this.newMessageNotificator = new NotificationWindow(this);
					this.newMessageNotificator.setPosition(NotificationWindow.BOTTOM_RIGHT);
				}
				this.newMessageNotificator.setMemberName(text);
				this.newMessageNotificator.setVisible(true);
				break;
			case 3:
				Toolkit.getDefaultToolkit().beep();
			}
		} else {
			// Disable notification
			if (this.newMessageNotificator != null) {
				this.newMessageNotificator.setVisible(false);
			}
		}
	}

	/** Rebuild all Plugin-Buttons in the Toolbar */
	public void updatePluginShortcuts() {
		String[] allEmbPlugins = this.theClient.getPluginShortcuts();
		JTalkerClientPlugInInterface tmpPlugin;
		this.jPanelPlugIns.removeAll();

		for (int i = 0; i < allEmbPlugins.length; i++) {
			tmpPlugin = this.myPluginLoader.getPluginByName(allEmbPlugins[i]);
			if (tmpPlugin != null) {
				JButton button = new JButton();
				button.setName(tmpPlugin.getClass().getName());
				button.setToolTipText("Plugin: " + tmpPlugin.getName());
				button.setMargin(new Insets(2, 2, 2, 2));
				button.setPreferredSize(new Dimension(48, 32));
				if (tmpPlugin.getIcon() == null) {
					button.setText(tmpPlugin.getName());
				} else {
					button.setIcon(tmpPlugin.getIcon());
				}
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						// TODO: search for a workaround!
						openPluginMainGUIFor(((JButton) evt.getSource()).getName());
					}
				});
				this.jPanelPlugIns.add(button);
			}
		}
	}

	/** Exit the Application */
	private void exitForm(WindowEvent evt) {// GEN-FIRST:event_exitForm
		if (this.isConnected)
			this.theClient.closeConnection();
		System.exit(0);
	}// GEN-LAST:event_exitForm

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				// Init JTalkerClient
				JTalkerClient jTalkerClient = new JTalkerClient();

				// Set Look and Feel
				try {
					UIManager.setLookAndFeel(jTalkerClient.guiPlaf);
				} catch (Exception e) {
					System.err.println("*** Can't set Look'n'Feel. Use default.");
				}

				// new JTalkerClientFront(jtc).show();
				new JTalkerClientFront(jTalkerClient).setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private JMenuItem jMenuItemConnect;
	private JMenuItem jMenuItemCommand;
	private JMenuItem jMenuItemChatroom;
	// private JComboBox jComboBoxRefresh;
	private JPanel jPanelStatus;
	private JToolBar jToolBar2;
	private JLabel jLabelVersion;
	private JCheckBoxMenuItem jCheckBoxMenuItemBusy;
	private JButton jButtonConnect;
	private JLabel jLabelStatusConnect;
	private JButton jButton1;
	private JButton jButtonConfig;
	private JMenuItem jMenuItemAccount;
	private JMenuItem jMenuItemAbout;
	private JMenu jMenuStatus;
	private JMenu jMenuPlugins;
	private JMenu jMenuAbout;
	private JPanel jPanelToolsT;
	private JScrollPane jScrollPaneMembers;
	private JList jListMembers;
	private JPanel jPanelMamberList;
	private JToolBar jToolBar1;
	private JPanel jPanelToolsR;
	private JButton jButtonOpen;
	private JButton jButtonMail;
	private JMenuItem jMenuItemSettings;
	private JMenuBar jMenuBarMain;
	private JToggleButton jToggleButtonStatus;
	private JMenuItem jMenuItemClose;
	private JMenu jMenuFile;
	private JButton jButtonReload;
	private JMenu jMenuServer;
	// End of variables declaration//GEN-END:variables
	public boolean isConnected = false;
	public boolean isLogedIn = false;
	public JTalkerClient theClient;
	private ClassLoader cl;
	private JTalkerFrontSettings mySettings = null;
	private JTalkerFrontCommand myCommandDialog = null;
	public boolean enableNotification = false; // Make some actions on new
												// message ;-)
	private JTalkerClientFrontPopUp userPopup = null;
	private NotificationWindow newMessageNotificator = null;
	private JTalkerClientPluginLoader myPluginLoader = null;
	public JTalkerClientPluginsInfo myPluginsInfoDialog = null;
	private ImageIcon connectPlainText = null;
	private ImageIcon connectEncrypted = null;

	private JPanel jPanelPlugIns;

	/** This class represents a List Row */
	class MyCellRenderer extends JLabel implements ListCellRenderer {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private ImageIcon userIcon = new ImageIcon(cl.getResource("com/jtalker/rs/icons/user.png"));
		private ImageIcon userMeIcon = new ImageIcon(cl.getResource("com/jtalker/rs/icons/me.png"));
		private ImageIcon userbIcon = new ImageIcon(cl.getResource("com/jtalker/rs/icons/user_busy.png"));
		private ImageIcon chatroomIcon = new ImageIcon(cl.getResource("com/jtalker/rs/icons/chatroom.png"));
		private ImageIcon newMailIcon = new ImageIcon(cl.getResource("com/jtalker/rs/icons/new_mail.png"));
		private JTalkerClientFront parent = null;

		public MyCellRenderer(JTalkerClientFront parent) {
			this.parent = parent;
		}

		// This is the only method defined by ListCellRenderer.
		// We just reconfigure the JLabel each time we're called.
		public Component getListCellRendererComponent(JList list, Object value, // value to display
				int index, // cell index
				boolean isSelected, // is the cell selected
				boolean cellHasFocus) // the list and the cell have the focus
		{
			if (value == null) {
				return null;
			}
			// System.out.println("-------[*]--------");
			MemberData memberData = (MemberData) value;
			String tmpName = memberData.name;
			this.setText(tmpName.replaceAll(" AT ", " @ "));

			if (memberData.hasNewMessage) {
				if (!memberData.name.equals(this.parent.theClient.userName)) {
					this.setIcon(this.newMailIcon);
					// Get focus, only if no chat window open
					if (!memberData.isChatWindowOpen()) {
						this.parent.notifyOnNewMessage(true, tmpName);
					}
				} else {
					this.setIcon(this.userMeIcon);
				}
			} else if (memberData.status.equals("busy")) {
				this.setIcon(this.userbIcon);
			} else if (memberData.type.equals(JTalkerParser.USER_TYPE_CHATROOM)) {
				this.setIcon(this.chatroomIcon);
			} else {
				this.parent.notifyOnNewMessage(false, null);
				if (memberData.short_name.equals(this.parent.theClient.userName)) {
					this.setIcon(this.userMeIcon);
				} else {
					this.setIcon(this.userIcon);
				}
			}

			if (isSelected) {
				this.setBackground(list.getSelectionBackground());
				this.setForeground(list.getSelectionForeground());
			} else {
				this.setBackground(list.getBackground());
				this.setForeground(list.getForeground());
			}

			this.setEnabled(list.isEnabled());
			this.setFont(list.getFont());
			this.setOpaque(true);

			if (!memberData.isConnected()) {
				// Mark off-line user
				this.setEnabled(false);
			}

			return this;
		}
	}

	/** Class for asynchronize updating the Window */
	public class UpdateTimer extends Thread {
		private JTalkerClientFront parent = null;

		public UpdateTimer(JTalkerClientFront parent) {
			this.parent = parent;
		}

		public void run() {
			while (true) {
				this.parent.refreshActionPerformed();
				try {
					// Reload every 2 second
					Thread.sleep(1000);
				} catch (Exception e) {
				}
			}

		}
	}

	/** This class represents an plug-in menu item */
	public class PlugInMenuItem extends JMenuItem {
		private static final long serialVersionUID = 1L;
		private String pluginClass = null;
		private int type = 0; // 0: mainGui, 1: Settings

		public PlugInMenuItem(String pluginClass, int type) {
			super();
			this.pluginClass = pluginClass;
			this.type = type;
		}
	}

}
